
# -*- coding: UTF-8 -*-
from django.shortcuts import render
from book.models import Book,loginUser,imgCagery,youHuiQuan,menuList
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse
from django.core import serializers
import json
from django.db.models import Q
from django.conf import settings
import os
import time
import base64
import ast


def add_book(request):
    print("add_book2...")
    data = json.loads(request.body.decode("utf-8"))
    print(data) # post
    # print(request.GET.get('book_name'),request.GET.get('test')) # get
    response = {}
    if not data["book_name"]:
        response['msg'] = "please input book name!"
        response['error_num'] = 1
        return JsonResponse(response)
    try:
         Book.objects.create(**data)

         response['msg'] = 'success'
         response['error_num'] = 0
    except Exception as e:
         response['msg'] = str(e)
         response['error_num'] = 1


    return JsonResponse(response)

# @require_http_methods(["GET"])
def show_books(request):
     response = {}
     try:
         books = Book.objects.all().order_by("-add_time")
         response['list'] = json.loads(serializers.serialize("json", books))


         response['msg'] = 'success'
         response['error_num'] = 0
     except Exception as e:
         response['msg'] = str(e)
         response['error_num'] = 1

     return JsonResponse(response)

def login(request):
    data = json.loads(request.body.decode("utf-8"))
    print(data)
    response = {}
    try:
        res = loginUser.objects.filter(name=data["name"],password=data["password"])
        print(list(res.values()))
        if res:
            response['msg'] = "登陆成功"
            response['token'] = str(time.time())
            response['user'] = list(res.values())
            response['code'] = 0
            return JsonResponse(response)
        else:
            response['msg'] = "用户名或密码错误"
            response['code'] = 1
            return JsonResponse(response)
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 1
def register(request):
    data = json.loads(request.body.decode("utf-8"))

    print(data)
    response = {}
    try:
        res = loginUser.objects.create(name=data["name"], password=data["password"])
        print(res)
        if res:
            response['msg'] = "注册成功，请登录"
            response['code'] = 0
            return JsonResponse(response)
        else:
            response['msg'] = "注册失败"
            response['code'] = 1
            return JsonResponse(response)
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 1


def build_menu(menu_items, parent_id=None):
    menu = []
    for item in menu_items:
        if item.parent_id == parent_id:
            child_menu = build_menu(menu_items, item.id)
            cc = child_menu
            menu.append({
                'id': item.id,
                'status': item.status,
                'type': item.type,
                'name': item.name,
                'icon': item.icon,
                'sort': item.sort,
                'frontpath': item.frontpath,
                'parent_id': parent_id,
                'child': child_menu

            })
    return menu
def getinfo(request):
    print("request*" * 10,)
    uid = request.GET.get('uid')
    print(uid )
    menus = [
        {
        "id":1,
        "status":1,
        "type":1,
        "name": "后台面板",
        "icon": "help",
        "child": [{
            "name": "主控台",
            "status": 0,
            "icon": "home-filled",
            "frontpath": "/",
        }]
        },
        {
            "id": 31,
            "type": 1,
            "status": 1,
            "name": "模版管理",
            "icon": "shopping-bag",
            "child": [
                {
                    "name": "抽屉模版",
                    "icon": "shopping-cart-full",
                    "frontpath": "/draw/list",
                },
                {
                    "name": "dialog模版",
                    "icon": "shopping-cart-full",
                    "frontpath": "/dialog/list",


                },
                {
                    "name": "前端分页模版",
                    "icon": "shopping-cart-full",
                    "frontpath": "/beforepage/list",

                },
            ],
        },
        # {   "id":2,
        #     "type": 1,
        #     "status": 1,
        #     "name": "管理员管理",
        #     "icon": "type",
        #     "frontpath": "/manager/list",
        # },
        {
        "id": 3,
            "type": 1,
            "status": 1,
            "name": "商城管理",
        "icon": "shopping-bag",
        "child": [
            {
            "name": "商品管理",
            "icon": "shopping-cart-full",
            "frontpath": "/goods/list",
            },
            {
            "name": "商品详情页",
            "icon": "shopping-cart-full",
            "frontpath": "/goods/detail/:id",
            "hidden": True,

            },
        ],
        },
        {"id": 4,
         "type": 1,
         "status": 1,
         "name": "分类管理",
            "icon": "type",
            "frontpath": "/category/list",
        },
        {"id": 5,
         "status": 1,
         "type": 1,
         "name": "用户列表",
            "icon": "Aim",
            "frontpath": "/user/list",
        },
        {"id": 6,
         "status": 1,
         "type": 1,
         "name": "订单列表",
            "icon": "shopping-cart-full",
            "frontpath": "/order/list",
        },
            {"id": 7,
             "status": 1,
             "type": 1,
             "name": "评价列表",
                "icon": "shopping-cart-full",
                "frontpath": "/comment/list",
            },
            {"id": 8,
             "status": 1,
             "type": 1,
             "name": "图库列表",
                "icon": "shopping-cart-full",
                "frontpath": "/image/list",
            },
            {"id": 9,
             "status": 1,
             "type": 1,
             "name": "公告列表",
             "icon": "shopping-cart-full",
             "frontpath": "/notice/list",

            },
        # {"id": 91,
        #  "status": 1,
        #  "type": 1,
        #  "name": "公告详情",
        #  "icon": "shopping-cart-full",
        #  "frontpath": "/notice/detail",
        #
        #  },
            {"id": 10,
             "status": 1,
             "type": 1,
             "name": "配置",
                "icon": "shopping-cart-full",

                "child": [{
                    "name": "权限管理",
                    "status": 1,
                    "icon": "shopping-cart-full",
                    "frontpath": "/access/list",
                }],
            },
            {"id":11,
             "status": 1,
             "type": 1,
             "name": "优惠券列表",
                "icon": "Tickets",
                "frontpath": "/coupon/list",
            },





    ]
    ruleNames = ['myChart,GET']

    # 取用户auth
    if uid:
        auth = loginUser.objects.get(id=uid).auth
        str_to_list = ast.literal_eval(auth)
        obj = menuList.objects.filter(status=1,id__in=sorted(str_to_list)).order_by('-sort')
        print(obj)
    else:
        # 递归
        obj = menuList.objects.filter(status=1).order_by('-sort')
    menu = build_menu(obj)


    # with open('book.json','w',encoding='utf-8') as f:
    #     f.write(json.dumps(menu,ensure_ascii=False))
    response = {
        "name":"admin",
        "menus":menu,
        "ruleNames":ruleNames
        }
    
    return JsonResponse(response)
def getALLMenu(request):
    obj = menuList.objects.all().order_by('-sort')
    menu = build_menu(obj)
    response = {
        "menus": menu,
    }
    return JsonResponse(response)

def updateMenuStatus(request):
    data = json.loads(request.body.decode("utf-8"))
    print(data)
    response = {}
    try:
        menuList.objects.filter(id=data['id']).update(status=data['status'])
        response['code'] = 0
        response['msg'] = '修改状态成功'
    except Exception as e:
        print(e)
        response['code'] = 1
        response['msg'] = '修改状态失败：%s'%e
    return JsonResponse(response)

def updateMenu(request):
    data = json.loads(request.body.decode("utf-8"))
    print(data)
    response = {}
    try:
        menuList.objects.filter(id=data['id']).update(
            type=data['type'],
            name=data['name'],
            icon=data['icon'],
            frontpath=data['frontpath'],
            sort=data['sort'],
            parent_id=data['rule_id'],
        )
        response['code'] = 0
        response['msg'] = '修改成功'

    except Exception as e:
        print(e)
        response['code'] = 1
        response['msg'] = '修改失败：%s' % e
    return JsonResponse(response)

def createMenu(request):
    data = json.loads(request.body.decode("utf-8"))
    print(data)
    response = {}
    try:
        menuList.objects.create(
            type=data['type'],
            name=data['name'],
            icon=data['icon'],
            frontpath=data['frontpath'],
            sort=data['sort'],
            parent_id=data['rule_id'],
        )
        response['code'] = 0
        response['msg'] = '创建成功'

    except Exception as e:
        print(e)
        response['code'] = 1
        response['msg'] = '创建失败：%s' % e
    return JsonResponse(response)

def delMenu(request):
    id = json.loads(request.body.decode("utf-8"))
    print(id)
    response = {}
    try:
        menuList.objects.filter(id=id).delete()

        response['code'] = 0
        response['msg'] = '删除成功'
    except Exception as e:
        print(e)
        response['code'] = 1
        response['msg'] = '删除失败：%s' % e
    return JsonResponse(response)

def updatepassword(request):
    data = json.loads(request.body.decode("utf-8"))

    print(data)
    response = {}
    try:
        res = loginUser.objects.filter(password=data["oldpassword"]).update(password=data["repassword"])

        response['msg'] = "修改密码成功，请重新登录～"
        response['code'] = 0
        return JsonResponse(response)




    except Exception as e:
        print("**13")
        response['msg'] = str(e)
        response['code'] = 1

def indexdata(request):
    response = {}
    data = [
        {"subTitle":"总支付订单",
        "subUnit":"个",
        "subValue":49,
        "title":"支付订单",
        "unit":"年",
        "unitColor":"success",
        "value":49},
        {"subTitle": "订单量",
         "subUnit": "个",
         "subValue": 409,
         "title": "支付订单",
         "unit": "年",
         "unitColor": "success",
         "value": 49},
        {"subTitle": "销售额",
         "subUnit": "个",
         "subValue": 149,
         "title": "支付订单",
         "unit": "年",
         "unitColor": "success",
         "value": 49},
        {"subTitle": "新增用户",
         "subUnit": "个",
         "subValue": 439,
         "title": "支付订单",
         "unit": "年",
         "unitColor": "success",
         "value": 49},
    ]
    data2 = [
        {"title":"用户",
        "icon": "UserFilled"},
        {"title": "商品",
         "icon": "InfoFilled"},
        {"title": "订单",
         "icon": "HomeFilled"},
        {"title": "评价",
         "icon": "HomeFilled"},
        {"title": "图库",
         "icon": "Ship"},
        {"title": "公告",
         "icon": "Ship"},
        {"title": "配置",
         "icon": "Ship"},
        {"title": "优惠券",
         "icon": "Ship"},


    ]

    response["data"]=data
    response["data2"]=data2
    return JsonResponse(response)

def myChart(request):
    response = {}
    data = request.GET.get("ectype")
    print(request.GET)
    response["x"]=['Mon01', 'Tue02', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    response["y"]=[120, 200, 150, 80, 70, 110, 130]
    return JsonResponse(response)

def getImageClassList(request):
    response = {}
    page = request.GET.get("page")
    limit = request.GET.get("limit")
    print(page,limit)
    ls2 = imgCagery.objects.all().order_by("-imgOrder")
    if ls2:
        ls2 = json.loads(serializers.serialize("json", ls2))
        # {'model': 'book.imgcagery', 'pk': 1, 'fields': {'name': '生鲜', 'imgOrder': '1'}},
        print(ls2)
        # ls2 = [{"id":1,"name":"家电"},{"id":2,"name":"服饰"},{"id":3,"name":"生鲜"},{"id":4,"name":"饮品"},{"id":5,"name":"母婴"}]
        page = int(page)   # 当前页
        limit = int(limit) # 每页几条
        index = page*limit
        # 分页
        if page == 1:
            response["list"] = ls2[:index]
        else:
            response["list"] = ls2[index - limit:index]
    else:

        response["list"] = []

    response["totalCount"] = len(ls2)
    return JsonResponse(response)

def createImageClass(request):
    data = json.loads(request.body.decode("utf-8"))

    print(data)
    response = {}
    try:
        res = imgCagery.objects.create(name=data["name"],imgOrder=str(data["order"]))
        # ls2 = imgCagery.objects.last().order_by("-imgOrder")
        # ls2 = json.loads(serializers.serialize("json", ls2))pytonp
        response['msg'] = "新增商品分类成功"
        response['code'] = 0
        return JsonResponse(response)
    except Exception as e:
        print("**13")
        response['msg'] = str(e)
        response['code'] = 1

def updateImageClass(request):
    data = json.loads(request.body.decode("utf-8"))
    print(data)
    response = {}
    try:
        res = imgCagery.objects.filter(id=data["editId"]).update(name=data["form"]["name"],imgOrder=data["form"]["order"])
        response['msg'] = "新增商品分类成功"
        response['code'] = 0
        return JsonResponse(response)
    except Exception as e:
        print("**13")
        response['msg'] = str(e)
        response['code'] = 1

def deleteImageClass(request):
    print("deleteImageClass...")
    data = json.loads(request.body.decode("utf-8"))
    print(data)
    response = {}
    try:
        res = imgCagery.objects.filter(id=data["imagId"]).delete()
        response['msg'] = "商品分类已删除"
        response['code'] = 0
        return JsonResponse(response)
    except Exception as e:
        print("**13")
        response['msg'] = str(e)
        response['code'] = 1

def getImageList(request):
    print("getImageList..........")
    response = {}
    page = request.GET.get("page")
    ide = request.GET.get("id")
    print(page, ide)
    # ls2 = imgCagery.objects.filter(id=ide)
    # ls2 = json.loads(serializers.serialize("json", ls2))
    if ide=="3" or ide=="4":
        ls2=[
            {"id":1,"name":"向日葵1212122212122212122212122222.jpg","url":"https://img2.baidu.com/it/u=1028011339,1319212411&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313"},
            {"id":2,"name":"向日葵2.jpg","url":"https://img2.baidu.com/it/u=1028011339,1319212411&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313"},
            {"id":3,"name":"向日葵3.jpg","url":"https://img2.baidu.com/it/u=1028011339,1319212411&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313"},
            {"id":4,"name":"向日葵4.jpg","url":"https://img2.baidu.com/it/u=1028011339,1319212411&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313"},
            {"id":5,"name":"向日葵5.jpg","url":"https://vcg05.cfp.cn/creative/vcg/400/new/VCG211455931784.jpg"},
        ]
    else:
        ls2 = [
            {"id":6,"name": "向日葵1212122212122212122212122222.jpg", "url": "https://t7.baidu.com/it/u=2984822884,629429889&fm=193&f=GIF"},
            {"id":7,"name": "向日葵1212122212122212122212122222.jpg", "url": "https://t7.baidu.com/it/u=2984822884,629429889&fm=193&f=GIF"},
            {"id":8,"name": "向日葵1212122212122212122212122222.jpg", "url": "https://t7.baidu.com/it/u=2984822884,629429889&fm=193&f=GIF"},
        ]
    response["totalCount"] = len(ls2)
    response["list"] = ls2
    return JsonResponse(response)


from django.core.files.storage import FileSystemStorage

from django.conf import settings
def upimage(request):
    print("upimage..........")
    print(request.FILES.get('img',None))
    img = request.FILES.get('img', None)
    response= {}
    if img:
        with open("./xxx.png","wb") as f:
            for i in img.chunks():
                f.write(i)
        response["msg"]="上传成功"
        response["code"] = 0
        return JsonResponse(response)
    else:
        print("no")
        response["msg"] = "上传失败"
        response["code"] = 1
        return JsonResponse(response)

def youhuiquan(request):
    print("youhuiquan..........")
    response = {}
    page = request.GET.get("page")
    limit = request.GET.get("limit")
    keyword = request.GET.get("keyword")
    print(page, limit,keyword)

    if keyword:
        ls2 = youHuiQuan.objects.all().filter(Q(title__icontains=keyword) | Q(price__icontains=keyword))
        ls2 = list(ls2.values())
    else:
        print("***",)
        ls2 = list(youHuiQuan.objects.all().order_by("-add_time").values())
    print("ls2:",ls2)
    if ls2:
        page = int(page)  # 当前页
        limit = int(limit)  # 每页几条
        index = page * limit
        # 分页
        if page == 1:
            response["list"] = ls2[:index]
        else:
            response["list"] = ls2[index - limit:index]
    else:
        response["list"] = []

    response["totalCount"] = len(ls2)
    return JsonResponse(response)


def search(request):
    print("search..........")
    response = {}
    keyword = request.GET.get("keyword")

    print(keyword)
    ls2 = youHuiQuan.objects.all().filter(Q(title__icontains=keyword) | Q(price__icontains=keyword))
    if ls2:
        ls2 = json.loads(serializers.serialize("json", ls2))
        response["list"] = ls2
    else:

        response["list"] = []
    print(response["list"])
    response["totalCount"] = len(ls2)
    return JsonResponse(response)

def updateDataClass(request):
    # 更新
    response = {}
    file = request.FILES.get("image")
    title = request.POST.get('title')
    price = request.POST.get('price')
    status = request.POST.get('status')
    id = request.POST.get('id')
    print(file, title, price, status,id)
    obj = youHuiQuan.objects.filter(id=id)
    # 处理图片
    if file:
        # 写
        pic_name = f'upload{str(time.time())[-4:]}.jpeg'
        path = os.path.join(settings.STATICFILES_DIRS[0], pic_name)
        with open(path, 'wb') as f:
            f.write(file.read())
        # 删除
        image = obj.values('image')[0]['image']
        print(image)
        if image:
            image = image.split("/")[-1]
            for i in os.listdir(settings.STATICFILES_DIRS[0]):
                if image == i:
                    os.remove(os.path.join(settings.STATICFILES_DIRS[0], image))


    try:
        if file:
            obj.update(image = "http://127.0.0.1:8000/static/%s" % pic_name,title=title,price=price,status=status)
        else:
            obj.update(title=title,price=price,status=status)

        response['code'] = 0
        response['msg'] = "修改成功"
    except Exception as e:
        response['code'] = 1
        response['msg'] = e
        print(e)
    return JsonResponse(response)


def addDataClass(request):
    response = {}
    file = request.FILES.get("image")
    title = request.POST.get('title')
    price = request.POST.get('price')
    status = request.POST.get('status')
    print(file,title, price,status)
    pic_name = f'upload{str(time.time())[-4:]}.jpeg'
    path = os.path.join(settings.STATICFILES_DIRS[0],pic_name)
    print(path)
    if file:
        with open(path, 'wb') as f:
            f.write(file.read())
    try:
        youHuiQuan.objects.create(
            title = title,
            price = price,
            image = "http://127.0.0.1:8000/static/%s"%pic_name,
            status = status
        )
        response['code'] = 0
        response['msg'] = "创建成功"
    except Exception as e:
        response['code'] = 1
        response['msg'] = e
        print(e)
    return JsonResponse(response)

def deleteDataClass(request):
    # 删除
    response = {}
    data = json.loads(request.body.decode("utf-8"))
    print(data)
    try:
        obj = youHuiQuan.objects.filter(id=data['id'])
        image = obj.values('image')[0]['image']
        print(image)
        if image:
            image = image.split("/")[-1]
            for i in os.listdir(settings.STATICFILES_DIRS[0]):
                if image == i:
                    os.remove(os.path.join(settings.STATICFILES_DIRS[0],image))

        obj.delete()
        response['code'] = 0
        response['msg'] = "删除成功"
    except Exception as e:
        response['code'] = 1
        response['msg'] = e
    return JsonResponse(response)



def getAllAuth(request):
    obj = menuList.objects.all()
    response = {"allAuth": list(obj.values())}
    return JsonResponse(response)

def updateUserAuth(request):
    response = {}
    data = json.loads(request.body.decode("utf-8"))
    print(data)
    print(list(set(data['authIds'])))
    try:
        obj = loginUser.objects.get(id=data['uid'])
        obj.auth = str(list(set(data['authIds'])))
        obj.save()
        response['code'] = 0
        response['msg'] = "权限设置成功"
    except Exception as e:
        response['code'] = 1
        response['msg'] = "权限设置失败：%s"%e
    return JsonResponse(response)


def getUserAuth(request):
    response = {}
    uid = request.GET.get('id')
    print("uid:",uid)
    if uid==None:
        obj = loginUser.objects.all()
        response = {"data": list(obj.values())}
    else:
        obj = loginUser.objects.get(id=uid)
        print(obj.auth)
        response['auths'] = obj.auth
    return JsonResponse(response)